package com.tensquare.user.interceptor;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Macross
 * @Type JwtInterceptor.java
 * @Desc Jwt拦截器,主要获取token中的权限
 * @date 2019/12/24 17:34
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头
        String header = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(header)) {
            //判断请求头字符串的开头中是否带有bearer
            if (header.startsWith("bearer ")){
                //截取请求头字符串,获取token
                String token = header.substring(7);
                //解析token,获取claims对象
                Claims claims = jwtUtil.parseToken(token);
                //判断claims是否为空
                if (claims != null) {
                    //放入request中
                    request.setAttribute("claims",claims);
                }
            }
        }
        //无论如何都放行
        return true;
    }
}
